package com.skivingcloud.admin.sys.controller;

import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.skivingcloud.admin.constants.Constant;
import com.skivingcloud.admin.security.SecurityUser;
import com.skivingcloud.admin.security.UserUtil;
import com.skivingcloud.admin.sys.entity.SysOrg;
import com.skivingcloud.admin.sys.service.SysOrgService;
import com.skivingcloud.common.utils.PageParameter;
import com.skivingcloud.common.utils.ReturnT;
import com.skivingcloud.common.utils.UuidUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;

/**
 *  控制层。
 *
 * @author skivingcloud
 * @since 2023-08-28
 */
@Tag(name = "SysOrgController", description = "机构管理API")
@RestController
@RequestMapping("/sysOrg/")
public class SysOrgController {
    private static final Logger log = LoggerFactory.getLogger(SysOrgController.class);
    @Resource
    private SysOrgService sysOrgService;

    /**
     * 添加。
     *
     * @param sysOrg 机构
     * @return {@code 0} 添加成功，{@code 500} 添加失败
     */
    @Operation(summary = "新增机构", description = "新增机构")
    @ApiResponse(responseCode = "2xx",description = "新增机构")
    @PostMapping("save")
    public ReturnT<Boolean> save(@Validated @RequestBody SysOrg sysOrg) {
        try{
            QueryWrapper queryWrapper = QueryWrapper.create();
            queryWrapper.where(SysOrg::getOrgCode).eq(sysOrg.getOrgCode());
            boolean exists = sysOrgService.exists(queryWrapper);
            if(exists){
                return ReturnT.error("机构编号重复！");
            }
            sysOrg.setId(UuidUtil.get32UUID());
            sysOrg.setCreater(UserUtil.getCurrentUser().getId());
            sysOrg.setCreateTime(LocalDateTime.now());
            return ReturnT.ok(sysOrgService.save(sysOrg));
        }catch(Exception e){
            log.error("保存机构失败", e);
            return ReturnT.error("保存机构失败！");
        }
    }

    /**
     * 根据主键删除。
     *
     * @param id 主键
     * @return {@code 0} 删除成功，{@code 500} 删除失败
     */
    @Operation(summary = "删除机构", description = "删除机构")
    @ApiResponse(responseCode = "2xx",description = "删除机构")
    @GetMapping("remove/{id}")
    public ReturnT<Boolean> remove(@PathVariable(name="id") Serializable id) {
        try{
            QueryWrapper queryWrapper = QueryWrapper.create();
            queryWrapper.where(SysOrg::getParentId).eq(id);
            boolean exists = sysOrgService.exists(queryWrapper);
            if(exists){
                return ReturnT.error("请先删除下级机构！");
            }
            return ReturnT.ok(sysOrgService.removeById(id));
        }catch(Exception e){
            log.error("删除机构失败", e);
            return ReturnT.error("删除机构失败！");
        }
    }

    /**
     * 根据主键更新。
     *
     * @param sysOrg 机构
     * @return {@code 0} 更新成功，{@code 500} 更新失败
     */
    @Operation(summary = "修改机构", description = "修改机构")
    @ApiResponse(responseCode = "2xx",description = "修改机构")
    @PostMapping("update")
    public ReturnT<Boolean> update(@Validated @RequestBody SysOrg sysOrg) {
        try{
            QueryWrapper queryWrapper = QueryWrapper.create();
            queryWrapper.where(SysOrg::getOrgCode).eq(sysOrg.getOrgCode())
                    .and(SysOrg::getId).ne(sysOrg.getId());
            boolean exists = sysOrgService.exists(queryWrapper);
            if(exists){
                return ReturnT.error("机构编号重复！");
            }
            sysOrg.setModUser(UserUtil.getCurrentUser().getId());
            sysOrg.setModTime(LocalDateTime.now());
            return ReturnT.ok(sysOrgService.updateById(sysOrg));
        }catch(Exception e){
            log.error("保存机构失败", e);
            return ReturnT.error("保存机构失败！");
        }
    }

    /**
     * 根据主键获取详细信息。
     *
     * @param id 主键
     * @return 详情
     */
    @Operation(summary = "根据主键获取机构", description = "根据主键获取机构")
    @ApiResponse(responseCode = "2xx",description = "根据主键获取机构")
    @GetMapping("getInfo/{id}")
    public ReturnT<SysOrg> getInfo(@PathVariable(name="id") Serializable id) {
        return ReturnT.ok(sysOrgService.getById(id));
    }

    /**
     * 分页查询。
     *
     * @param parameter 分页对象
     * @return 分页对象
     */
    @Operation(summary = "分页查询机构", description = "分页查询机构")
    @ApiResponse(responseCode = "2xx",description = "分页查询机构")
    @PostMapping("page")
    public ReturnT<Page<SysOrg>> page(@RequestBody PageParameter<SysOrg> parameter) {
        return ReturnT.ok(sysOrgService.queryByPage(parameter));
    }
    
    /**
     * 获取树形机构
     *
     * @return 树形机构
     */
    @Operation(summary = "查询树形机构", description = "查询树形机构")
    @ApiResponse(responseCode = "2xx",description = "查询树形机构")
    @GetMapping("treeList/{tenantId}")
    public ReturnT<List<SysOrg>> treeList(@PathVariable("tenantId") String tenantId){
        SecurityUser user = UserUtil.getCurrentUser();
        if (!Constant.SUPER_ADMIN_TENANT_ID.equals(user.getTenantId())) {
            return ReturnT.ok(sysOrgService.getAllOrgTreeUtils(user.getTenantId()));
        } else {
            return ReturnT.ok(sysOrgService.getAllOrgTreeUtils());
        }
    }
    
    /**
     * 根据租户查询树形机构
     * @param tenantId 租户id
     * @return 结果
     */
    @Operation(summary = "根据租户查询树形机构", description = "根据租户查询树形机构")
    @ApiResponse(responseCode = "2xx",description = "根据租户查询树形机构")
    @GetMapping("treeListByTenantId/{tenantId}")
    public ReturnT<List<SysOrg>> treeListByTenantId(@PathVariable("tenantId") String tenantId){
        return ReturnT.ok(sysOrgService.getAllOrgTreeUtils(tenantId));
    }
}
